# -*- coding:utf-8 -*-

from typing import List
from datetime import datetime, time
from module_admin.entity.do.role_do import SysRoleDept
from sqlalchemy import and_, delete, desc, func, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from module_gen.constants.gen_constants import GenConstants
from module_vip.entity.do.bg_download_record_do import BgDownloadRecord
from module_vip.entity.vo.bg_download_record_vo import BgDownloadRecordPageModel, BgDownloadRecordModel
from utils.page_util import PageUtil, PageResponseModel
from utils.common_util import CamelCaseUtil
from datetime import date


class BgDownloadRecordDao:

    @classmethod
    async def get_by_id(cls, db: AsyncSession, bg_download_record_id: int) -> BgDownloadRecord:
        """根据主键获取单条记录"""
        bg_download_record = (((await db.execute(
                            select(BgDownloadRecord)
                            .where(BgDownloadRecord.id == bg_download_record_id)))
                       .scalars())
                       .first())
        return bg_download_record

    """
    查询
    """
    @classmethod
    async def get_bg_download_record_list(cls, db: AsyncSession,
                             query_object: BgDownloadRecordPageModel,
                             data_scope_sql: str = None,
                             is_page: bool = False) -> [list | PageResponseModel]:

        query = (
            select(BgDownloadRecord)
            .where(
                BgDownloadRecord.create_time.between(query_object.begin_create_time, query_object.end_create_time) if query_object.create_time else True,
                BgDownloadRecord.file_id == query_object.file_id if query_object.file_id else True,
                BgDownloadRecord.user_id == query_object.user_id if query_object.user_id else True,
                BgDownloadRecord.del_flag == '0',
                eval(data_scope_sql) if data_scope_sql else True,
            )
            .order_by(desc(BgDownloadRecord.create_time))
            .distinct()
        )
        bg_download_record_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
        return bg_download_record_list


    @classmethod
    async def add_bg_download_record(cls, db: AsyncSession, add_model: BgDownloadRecordModel, auto_commit: bool = True) -> BgDownloadRecordModel:
        """
        增加
        """
        bg_download_record =  BgDownloadRecord(**add_model.model_dump(exclude_unset=True, ))
        db.add(bg_download_record)
        await db.flush()
        bg_download_record_model = BgDownloadRecordModel(**CamelCaseUtil.transform_result(bg_download_record))
        if auto_commit:
            await db.commit()
        return bg_download_record_model

    @classmethod
    async def edit_bg_download_record(cls, db: AsyncSession, edit_model: BgDownloadRecordModel, auto_commit: bool = True) -> BgDownloadRecord:
        """
        修改
        """
        edit_dict_data = edit_model.model_dump(exclude_unset=True, exclude={ *GenConstants.DAO_COLUMN_NOT_EDIT })
        await db.execute(update(BgDownloadRecord), [edit_dict_data])
        await db.flush()
        if auto_commit:
            await db.commit()
        return await cls.get_by_id(db, edit_model.id)

    @classmethod
    async def del_bg_download_record(cls, db: AsyncSession, bg_download_record_ids: List[str], soft_del: bool = True, auto_commit: bool = True):
        """
        删除
        """
        if soft_del:
            await db.execute(update(BgDownloadRecord).where(BgDownloadRecord.id.in_(bg_download_record_ids)).values(del_flag='2'))
        else:
            await db.execute(delete(BgDownloadRecord).where(BgDownloadRecord.id.in_(bg_download_record_ids)))
        await db.flush()
        if auto_commit:
            await db.commit()

    @classmethod
    async def get_download_statistics(cls, db: AsyncSession) -> dict:
        """
        获取下载统计信息
        """
        # 总下载次数
        total_query = select(func.count(BgDownloadRecord.id)).where(BgDownloadRecord.del_flag == '0')
        total_result = await db.execute(total_query)
        total_downloads = total_result.scalar()

        # 成功下载次数
        success_query = select(func.count(BgDownloadRecord.id)).where(
            BgDownloadRecord.download_status == '1',
            BgDownloadRecord.del_flag == '0'
        )
        success_result = await db.execute(success_query)
        success_downloads = success_result.scalar()

        # 失败下载次数
        failed_query = select(func.count(BgDownloadRecord.id)).where(
            BgDownloadRecord.download_status == '0',
            BgDownloadRecord.del_flag == '0'
        )
        failed_result = await db.execute(failed_query)
        failed_downloads = failed_result.scalar()

        # 今日下载次数
        today = date.today()
        today_query = select(func.count(BgDownloadRecord.id)).where(
            func.date(BgDownloadRecord.create_time) == today,
            BgDownloadRecord.del_flag == '0'
        )
        today_result = await db.execute(today_query)
        today_downloads = today_result.scalar()

        return {
            'totalDownloads': total_downloads,
            'successDownloads': success_downloads,
            'failedDownloads': failed_downloads,
            'todayDownloads': today_downloads
        }

    @classmethod
    async def get_user_today_download_times(cls, query_db: AsyncSession, user_id: int) -> int:
        today = date.today()
        today_query = select(func.count(BgDownloadRecord.id)).where(
            func.date(BgDownloadRecord.create_time) == today,
            BgDownloadRecord.user_id == user_id,
            BgDownloadRecord.del_flag == '0'
        )
        today_result = await query_db.execute(today_query)
        today_downloads = today_result.scalar()
        return today_downloads